package com.like.bluetooth.classic.client.scan.callback

import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.like.bluetooth.callback.BluetoothCallback
import com.like.bluetooth.util.ScanResult

class ScanCallbackManager {
    private val broadcastReceiver by lazy {
        object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (intent?.action == BluetoothDevice.ACTION_FOUND) {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE) ?: return
                    val rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, 0)
                    scanBluetoothCallback?.onSuccess(ScanResult(device, rssi.toInt(), null))
                }
            }
        }
    }

    private var scanBluetoothCallback: BluetoothCallback<ScanResult>? = null


    fun registerBroadcastReceiver(context: Context) {
        context.registerReceiver(broadcastReceiver, IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND) // 发现设备
        })
    }

    fun unregisterBroadcastReceiver(context: Context) {
        try {
            context.unregisterReceiver(broadcastReceiver)
        } catch (e: Exception) {
        }
    }

    fun setScanBleCallback(callback: BluetoothCallback<ScanResult>?) {
        scanBluetoothCallback = callback
    }

}
